package com.realestate.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.realestate.constants.ComUnitName;
import com.realestate.constants.RecordStatus;
import com.realestate.model.BrtbDistrict;
import com.realestate.model.QBrtbDistrict;
import com.realestate.model.QBrtbProvince;
import com.trg.dao.jpa.GenericDAOImpl;

@Repository
public class DistrictDaoImpl extends GenericDAOImpl<BrtbDistrict, Long> implements DistrictDao{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = Logger.getLogger(DistrictDaoImpl.class);
	
	@Override
	@PersistenceContext(unitName = ComUnitName.COM_UNIT)
	public void setEntityManager(EntityManager entityManager) {
		super.setEntityManager(entityManager);
	}

	@Override
	public List<BrtbDistrict> getDistrictByProvinceCode(String provinceCode) {
		JPQLQuery query = new JPAQuery(em());
		
		QBrtbProvince province = QBrtbProvince.brtbProvince;
		QBrtbDistrict district = QBrtbDistrict.brtbDistrict;
		
		BooleanBuilder where = new BooleanBuilder();

		where.and(province.recordStatus.eq(RecordStatus.O))
			 .and(district.recordStatus.eq(RecordStatus.O))
			 .and(province.provinceCode.eq(provinceCode));
		
		query.from(district).leftJoin(district.brtbProvince, province).where(where);
		
		List<BrtbDistrict> districts = query.list(district);
		return districts;
	}

	@Override
	public BrtbDistrict getDistrictByDistrictCode(String code) {
		JPQLQuery query = new JPAQuery(em());
		QBrtbDistrict district = QBrtbDistrict.brtbDistrict;
		
		query.from(district);
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(district.recordStatus.eq(RecordStatus.O)).and(district.districtCode.eq(code));
		
		query.where(where);
		
		BrtbDistrict districtResult = query.uniqueResult(district);
		return districtResult;
	}

}
